<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage as $message } from 'element-plus'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

const loginFormRef = ref()
const loginStatusRef = ref<boolean>(false)
const loginFormRules = reactive({
  userName: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
  ],
  passWord: [
    {
      required: true,
      message: '请输入用户密码',
      trigger: 'blur',
    },
  ],
})
const loginForm = reactive({
  userName: '',
  passWord: '',
})

const onSubmit = async () => {
  if (!loginFormRef) return
  loginStatusRef.value = true
  await loginFormRef.value.validate(async (isValide) => {
    if (isValide) {
      try {
        await userStore.login(loginForm)
        $message.success('登录成功！')
        const { redirect }: any = route.query
        router.push({
          path: redirect || '/',
        })
      } catch (error) {
        $message.error((error as Error).message)
      }
    }
  })
  loginStatusRef.value = false
}
</script>

<template>
  <div class="container">
    <div class="loginForm">
      <!-- <div class="title">登录</div> -->
      <el-form
        ref="loginFormRef"
        :rules="loginFormRules"
        :model="loginForm"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loginForm.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="loginForm.passWord" />
        </el-form-item>
        <el-form-item class="submitBtn">
          <el-button :loading="loginStatusRef" type="primary" @click="onSubmit()">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  width: 100vw;
  height: 100vh;
  background: #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  .loginForm {
    width: 500px;
    margin: 0 auto;
    background: #fff;
    border-radius: 5px;
    padding: 30px;
    padding-top: 48px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    .submitBtn {
      :deep(.el-form-item__content) {
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>
